package com.qf.dao.impl;

import com.qf.dao.StuDao;
import com.qf.domain.Stu;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.awt.print.Book;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class StuDaoImpl implements StuDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public Stu selectByStuName(String stuname) {
        String sql=" SELECT * FROM `stuinfo` WHERE `stuname`=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Stu.class),stuname);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Stu> selectAll() {
        String sql=" SELECT `id`,`stuname`,`stuno`,`idcard`,`startdate`,`status` FROM `stuinfo` ";
        try {
            //return queryRunner.query(sql,new BeanListHandler<>(Stu.class));
            return  queryRunner.query(sql,new BeanListHandler<>(Stu.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertStu(Stu stu) {
        String sql=" INSERT INTO `stuinfo` (`stuname`,`stuno`,`pwd`,`idcard`,`startdate`,`status`) VALUES(?,?,?,?,?,?) ";
        Object[] params={stu.getStuname(),stu.getStuno(),stu.getPwd(),stu.getIdcard(),stu.getStartdate(),stu.getStatus()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Stu stu) {
        String sql=" UPDATE `stuinfo` SET `stuname`=?,`stuno`=?,`pwd`=?,`idcard`=?,`startdate`=?,`status`=? WHERE `id`=? ";
        Object[] params={stu.getStuname(),stu.getStuno(),stu.getPwd(),stu.getIdcard(),stu.getStartdate(),stu.getStatus(),stu.getId()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Stu selectById(int id) {
        String sql=" SELECT `id`,`stuname`,`stuno`,`pwd`,`idcard`,`startdate`,`status` FROM `stuinfo` WHERE id=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Stu.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id) {
        String sql=" DELETE FROM `stuinfo` WHERE `id`=? ";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
